import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Radio, Button, Icon, Upload,
} from 'antd';
import { phone, email } from '@/utils/regular';
import { connect } from 'dva';

const FormItem = Form.Item;
const { TextArea } = Input;

const RadioGroup = Radio.Group;


@connect(({ packing }) => ({
  packing,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      iconList: [],
      remarkList: [],
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }


  handleChange = (type, info) => {
    let logoList = info;
    logoList = logoList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    logoList = logoList.filter((file) => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });
    if (type === 'remark') {
      this.setState({ remarkList: logoList });
    } else {
      this.setState({ iconList: logoList });
    }
  };
  RemarkCustomRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            remark: res.msg.url,
          });
          _this.handleChange('remark', [obj]);
        }
      },
    });


  };
  iconCustomRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            merchantIcon: res.msg.url,
          });
          _this.handleChange('icon', [obj]);
        }
      },
    });


  };
  // 表单
  renderContent = () => {
    const { form, values, brandLists } = this.props;
    const { iconList, remarkList } = this.state;
    const iconProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      customRequest: this.iconCustomRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    const remarkProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      customRequest: this.RemarkCustomRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    return [
      <FormItem key="brandName" {...this.formLayout} label="商户名称">
        {form.getFieldDecorator('merchantName', {
          rules: [{ required: true, message: '请输入商户名称！' }],
          initialValue: values.merchantName,
        })(<Input maxLength={40} placeholder="请输入"/>)}
      </FormItem>,
      <FormItem key="brandNo" {...this.formLayout} label="品牌名称">
        {form.getFieldDecorator('brandNo', {
          rules: [{ required: true, message: '请输入品牌名称！' }],
          initialValue: values.brandNo,
        })(<Select placeholder="请输入品牌名称" style={{ width: '100%' }}>
          {
            brandLists.map(item => (
              <Select.Option key={item.brandNo} value={item.brandNo}>{item.brandName}</Select.Option>
            ))
          }
        </Select>)}
      </FormItem>,

      <FormItem key="merchantIcon" {...this.formLayout} label="ICON">
        {
          iconList.length > 0 ?
            form.getFieldDecorator('merchantIcon', {
              rules: [{ required: true, message: '请上传商户icon！' }],
              initialValue: values.merchantIcon,
            })(
              <Upload {...iconProps} fileList={iconList}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) : form.getFieldDecorator('merchantIcon', {
              rules: [{ required: true, message: '请上传商户icon！' }],
              initialValue: values.merchantIcon,
            })(
            <Upload {...iconProps} fileList={
              values.merchantIcon ? [{
                name: values.merchantIcon,
                uid: 1,
                url: values.merchantIcon,
              }] : []
            }>
              <Icon type="upload"/> 上传
            </Upload>,
            )}
      </FormItem>,
      <FormItem key="status" {...this.formLayout} label="状态">
        {form.getFieldDecorator('status', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.status,
        })(
          <RadioGroup>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>暂停</Radio>
          </RadioGroup>,
        )}
      </FormItem>,
      <FormItem key="remark" {...this.formLayout} label="商户描述">
        {
          remarkList.length > 0 ?
            form.getFieldDecorator('remark', {
              rules: [{ required: true, message: '请上传商户描述！' }],
              initialValue: values.remark,
            })(
              <Upload {...remarkProps} fileList={remarkList}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) : form.getFieldDecorator('remark', {
              rules: [{ required: true, message: '请上传商户描述！' }],
              initialValue: values.remark,
            })(
            <Upload {...remarkProps} fileList={
              values.remark ? [{
                name: values.remark,
                uid: 1,
                url: values.remark,
              }] : []
            }>
              <Icon type="upload"/> 上传
            </Upload>,
            )}
      </FormItem>,

    ];
  };

  //弹窗
  render() {
    const { updateModalVisible, handleUpdateModalVisible, modalVisible } = this.props;
    //完成
    const handleNext = () => {
      const { form, values, handleUpdate, handleAdd, modalVisible } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...values, ...fieldsValue };

        if (modalVisible) {
          handleAdd(formVals);
        } else {
          handleUpdate(formVals);
        }
        this.setState({
          iconList: [],
        });
      });
    };
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title={modalVisible ? '新增商户' : '修改商户'}
        visible={updateModalVisible}
        onOk={handleNext}
        onCancel={() => handleUpdateModalVisible(false, [])}
      >
        {this.renderContent()}
      </Modal>
    );
  }
}

export default UpdateForm;
